import { reqShopCart, reqDeleteCartById, reqUpdataCheckedById } from "@/api";
const state = {
    recartList: []
};

const mutations = {
    GETCARTLIST(state, cartList) {
        state.recartList = cartList
    }
};

const actions = {
    // 获取购物车某一个产品
    async getCartList({ commit }) {
        let result = await reqShopCart();
        if (result.code == 200) {
            commit("GETCARTLIST", result.data)
        }
    },
    // 删除购物车某一个产品
    async deleteCartListBySkuId({ commit }, skuId) {
        let result = await reqDeleteCartById(skuId);
        if (result.code == 200) {
            return "ok";
        } else {
            return Promise.reject(new Error('faile'));
        }
    },
    // 修改购物车某一产品的选中状态
    async UpdataCheckedById({ commit }, { skuId, isChecked }) {
        let result = await reqUpdataCheckedById(skuId, isChecked);
        if (result.code == 200) {
            return "ok";
        } else {
            return Promise.reject(new Error('faile'));
        }
    },
    deleteAllCheckedCart({ dispatch, getters }) {
        let PromiseAll = [];
        getters.cartList.cartInfoList.forEach(item => {
            let promise = item.isChecked == 1 ? dispatch('deleteCartListBySkuId', item.skuId) : "";
            PromiseAll.push(promise)
        });
        return Promise.all(PromiseAll)
    },
    // 修改全部产品状态
    updateAllCartChecked({ dispatch, state }, isChecked) {
        console.log(state)
        console.log(isChecked)
        let promiseAll = [];
        state.recartList[0].cartInfoList.forEach(item=> {
            let promise = dispatch("UpdataCheckedById", {
                skuId: item.skuId,
                isChecked:isChecked,
            });
            promiseAll.push(promise)
        });
        return Promise.all(promiseAll)
    }
};

const getters = {
    cartList(state) {
        return state.recartList[0] || {}
    },

};

export default {
    state, mutations, actions, getters
}